<?php
namespace app\admin\controller;
use think\Controller;
use think\captcha\Captcha;
use think\Db;
use think\Session;
use app\admin\model\Setup as SetupModel;
use app\admin\model\Log as LogModel;
class Login extends Controller
{
    /**
     * 构造函数
     */
    public function _initialize()
    {
        //取网站设置
        $SetupModel = new SetupModel();
        $setup = $SetupModel->findsetup(1);
        //存入session
        Session::set("setup",$setup);//取网站设置
    }
    /**
     * 登陆页
     * @return mixed
     */
    public function login()
    {
        if (!empty(Session::has('admin'))) {
            //说明已经登录了，直接跳转
            $this->redirect('admin/index/index');
        }
        if (request()->isPost()) {
            //开始验证
            if (!$this->checkVerify(input('post.verifycode'))) {
                //说明验证码错误
                return json(['data'=>'','code'=>1,'message'=>'验证码错误']);
            }
            $user = Db::name('manage')->where(['username' => input('post.username')])->find();
            if (empty($user)) {
                //说明用户名错误
                return json(['data'=>'','code'=>1,'message'=>'用户名错误']);
            }
            if($user['password'] !=  md5(input('post.password'))) {
                //说明密码错误
                return json(['data'=>'','code'=>1,'message'=>'密码错误']);
            }
            //存入session
            Session::set("admin",$user);
            //写入登录日志
            $LogModel = new LogModel();
            $type = 'login';
            $log_value = $this->getInfo();
            $manage_id = $user['manage_id'];
            $LogModel->addLog($type,$log_value,$manage_id);
            return json(['data'=>$user,'code'=>0,'message'=>'成功']);
        }
        return $this->fetch();
    }

    /**
     * 取系统信息
     */
    protected function getInfo()
    {
        $data = [
            'time' => time(),
            'ip' => get_real_ip(),
            'broswer' => get_broswer(),
            'os' => get_os()
        ];
        return json_encode($data);
    }

    /**
     * 验证码
     * @return mixed
     */
    public function verify()
    {
        $config =    [
            // 验证码字体大小
            'fontSize'    =>    30,
            // 验证码位数
            'length'      =>    4,
            // 关闭验证码杂点
            'useNoise'    =>    false,
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }

    /**
     * 检查验证码是否正确
     * @param $code
     * @param string $id
     * @return bool
     */
    protected function checkVerify($code, $id = '')
    {
        $captcha = new Captcha();
        return $captcha->check($code, $id);
    }

    public function outLogin()
    {
        Session::delete('admin');
        if(Session::has('admin')) {
            return $this->error('退出失败');
        } else {
            $this->redirect('admin/login/login');
        }
    }
}
